package com.yanxx.codegenerator.impl;

import com.yanxx.codegenerator.storage.CodeGeneratorState;
import com.yanxx.codegenerator.storage.CodeGeneratorStorage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 带持久化功能的编码生成器
 * 继承自SequentialCodeGenerator，增加了状态持久化功能
 */
public class PersistentCodeGenerator extends SequentialCodeGenerator {
    private static final Logger logger = LoggerFactory.getLogger(PersistentCodeGenerator.class);
    
    private final CodeGeneratorStorage storage;
    
    /**
     * 构造函数
     *
     * @param prefix     编号前缀
     * @param codeLength 编号长度（不包括前缀）
     * @param startValue 起始编号值
     * @param storage    存储实现
     */
    public PersistentCodeGenerator(String prefix, int codeLength, long startValue, CodeGeneratorStorage storage) {
        super(prefix, codeLength, startValue);
        this.storage = storage;
    }
    
    /**
     * 使用默认配置和指定存储的构造函数
     *
     * @param storage 存储实现
     */
    public PersistentCodeGenerator(CodeGeneratorStorage storage) {
        super();
        this.storage = storage;
    }
    
    @Override
    public void initialize() {
        super.initialize();
        
        if (storage == null) {
            logger.warn("Storage is null, skipping initialization from storage");
            return;
        }
        
        // 从存储中加载状态
        CodeGeneratorState state = storage.load();
        if (state != null) {
            // 恢复当前最大值
            currentMaxValue.set(state.getCurrentMaxValue());
            
            // 恢复已确认的编号
            confirmedCodes.clear();
            confirmedCodes.addAll(state.getConfirmedCodes());
            
            // 恢复待回收的编号
            pendingCodes.clear();
            pendingCodes.addAll(state.getPendingCodes());
            
            // 恢复已回收的编号
            recycledCodes.clear();
            recycledCodes.addAll(state.getRecycledCodes());
            
            logger.info("Successfully initialized from storage, currentMaxValue: {}, confirmedCodes: {}, pendingCodes: {}, recycledCodes: {}",
                    state.getCurrentMaxValue(), state.getConfirmedCodes().size(), state.getPendingCodes().size(), state.getRecycledCodes().size());
        } else {
            logger.warn("Failed to load state from storage, using default initialization");
        }
    }
    
    @Override
    public void shutdown() {
        super.shutdown();
        
        if (storage == null) {
            logger.warn("Storage is null, skipping saving to storage");
            return;
        }
        
        // 保存状态到存储
        boolean saved = storage.save(
                currentMaxValue.get(),
                confirmedCodes,
                pendingCodes,
                recycledCodes
        );
        
        if (saved) {
            logger.info("Successfully saved state to storage");
        } else {
            logger.error("Failed to save state to storage");
        }
    }
    
    @Override
    public String generate() {
        String code = super.generate();
        saveState();
        return code;
    }
    
    @Override
    public boolean recycle(String code) {
        boolean result = super.recycle(code);
        if (result) {
            saveState();
        }
        return result;
    }
    
    @Override
    public boolean confirm(String code) {
        boolean result = super.confirm(code);
        if (result) {
            saveState();
        }
        return result;
    }
    
    /**
     * 保存当前状态到存储
     */
    private void saveState() {
        if (storage != null) {
            storage.save(
                    currentMaxValue.get(),
                    confirmedCodes,
                    pendingCodes,
                    recycledCodes
            );
        }
    }
}